package com.ruoyi.procurementmanagement.service.impl;

import java.util.List;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.finance.domain.ErpFinanceItem;
import com.ruoyi.finance.service.IErpFinanceItemService;
import com.ruoyi.procurementmanagement.domain.ErpWarehouseEntry;
import com.ruoyi.procurementmanagement.service.IErpWarehouseEntryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.procurementmanagement.mapper.ErpSupplierSettlementMapper;
import com.ruoyi.procurementmanagement.domain.ErpSupplierSettlement;
import com.ruoyi.procurementmanagement.service.IErpSupplierSettlementService;
import org.springframework.transaction.annotation.Transactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


/**
 * 供应商结算单Service业务层处理
 *
 * @author ruoyi
 * @date 2025-03-20
 */
@Slf4j
@Service
public class ErpSupplierSettlementServiceImpl implements IErpSupplierSettlementService
{
    @Autowired
    private ErpSupplierSettlementMapper erpSupplierSettlementMapper;

    // 添加财务服务依赖
    @Autowired
    private IErpFinanceItemService erpFinanceItemService;

    @Autowired
    private IErpWarehouseEntryService erpWarehouseEntryService;


    @Override
    @Transactional
    public int cancelErpSupplierSettlement(Long id) {
        // 1. 获取结算单信息
        ErpSupplierSettlement settlement = erpSupplierSettlementMapper.selectErpSupplierSettlementById(id);
        if (settlement == null) {
            log.error("结算单不存在，ID: {}", id);
            throw new RuntimeException("结算单不存在");
        }

        // 2. 删除关联的财务记录
        int financeDeleteCount = erpFinanceItemService.deleteErpFinanceItemBySourceSn(settlement.getSn());
        log.info("删除财务记录数量: {}", financeDeleteCount);

        // 3. 获取关联的入库单ID列表
        List<Long> entryIds = erpSupplierSettlementMapper.selectEntryIdsBySettlementId(id);
        log.info("关联入库单ID: {}", entryIds);

        // 4. 更新关联入库单状态
        if (entryIds != null && !entryIds.isEmpty()) {
            for (Long entryId : entryIds) {
                ErpWarehouseEntry entry = new ErpWarehouseEntry();
                entry.setId(entryId);
                entry.setStatus("审核通过");
                entry.setSupplierSettlementFlag(0);
                entry.setSupplierSettlementId(null);
                int updateCount = erpWarehouseEntryService.updateErpWarehouseEntry(entry);
                log.info("更新入库单ID: {}, 结果: {}", entryId, updateCount);
            }

            // 5. 删除关联关系
            int relationDeleteCount = erpSupplierSettlementMapper.deleteSettlementEntryRelationBySettlementId(id);
            log.info("删除关联关系数量: {}", relationDeleteCount);
        }

        // 6. 删除结算单
        int deleteCount = erpSupplierSettlementMapper.deleteErpSupplierSettlementById(id);
        log.info("删除结算单结果: {}", deleteCount);

        return deleteCount;
    }

    /**
     * 查询供应商结算单
     *
     * @param id 供应商结算单主键
     * @return 供应商结算单
     */
    @Override
    public ErpSupplierSettlement selectErpSupplierSettlementById(Long id)
    {
        return erpSupplierSettlementMapper.selectErpSupplierSettlementById(id);
    }

    /**
     * 查询供应商结算单列表
     *
     * @param erpSupplierSettlement 供应商结算单
     * @return 供应商结算单
     */
    @Override
    public List<ErpSupplierSettlement> selectErpSupplierSettlementList(ErpSupplierSettlement erpSupplierSettlement)
    {
        return erpSupplierSettlementMapper.selectErpSupplierSettlementList(erpSupplierSettlement);
    }

    /**
     * 新增供应商结算单
     *
     * @param erpSupplierSettlement 供应商结算单
     * @return 结果
     */
    @Override
    @Transactional
    public int insertErpSupplierSettlement(ErpSupplierSettlement erpSupplierSettlement) {
        erpSupplierSettlement.setCreateTime(DateUtils.getNowDate());
        int result = erpSupplierSettlementMapper.insertErpSupplierSettlement(erpSupplierSettlement);

        if (result > 0 && erpSupplierSettlement.getEntryIds() != null) {
            for (Long entryId : erpSupplierSettlement.getEntryIds()) {
                // 确保使用正确的参数顺序和名称
                erpSupplierSettlementMapper.insertSettlementEntryRelation(
                        erpSupplierSettlement.getId(), // 对应 settlementId
                        entryId                       // 对应 entryId
                );

                // 更新入库单状态
                ErpWarehouseEntry entry = new ErpWarehouseEntry();
                entry.setId(entryId);
                entry.setStatus("已结算");
                entry.setSupplierSettlementFlag(1);
                entry.setSupplierSettlementId(erpSupplierSettlement.getId());
                erpWarehouseEntryService.updateErpWarehouseEntry(entry);
            }
        }
        return result;
    }

    /**
     * 修改供应商结算单
     *
     * @param erpSupplierSettlement 供应商结算单
     * @return 结果
     */
    @Override
    public int updateErpSupplierSettlement(ErpSupplierSettlement erpSupplierSettlement) {
        erpSupplierSettlement.setUpdateTime(DateUtils.getNowDate());
        int result = erpSupplierSettlementMapper.updateErpSupplierSettlement(erpSupplierSettlement);

        if (result > 0) {
            // 更新对应的财务支出记录
            ErpFinanceItem query = new ErpFinanceItem();
            query.setSourceType("供应商结算");
            query.setSourceSn(erpSupplierSettlement.getSn());
            List<ErpFinanceItem> financeItems = erpFinanceItemService.selectErpFinanceItemList(query);

            if (!financeItems.isEmpty()) {
                ErpFinanceItem financeItem = financeItems.get(0);
                financeItem.setAmount(erpSupplierSettlement.getTotalPrice());
                financeItem.setUpdater(erpSupplierSettlement.getUpdater());
                erpFinanceItemService.updateErpFinanceItem(financeItem);
            }
        }

        return result;
    }

    @Override
    public int deleteErpSupplierSettlementById(Long id) {
        ErpSupplierSettlement settlement = erpSupplierSettlementMapper.selectErpSupplierSettlementById(id);
        if (settlement != null) {
            // 删除关联的财务记录
            ErpFinanceItem query = new ErpFinanceItem();
            query.setSourceType("供应商结算");
            query.setSourceSn(settlement.getSn());
            List<ErpFinanceItem> financeItems = erpFinanceItemService.selectErpFinanceItemList(query);

            if (!financeItems.isEmpty()) {
                erpFinanceItemService.deleteErpFinanceItemByIds(
                        financeItems.stream().map(ErpFinanceItem::getId).toArray(Integer[]::new)
                );
            }
        }
        return erpSupplierSettlementMapper.deleteErpSupplierSettlementById(id);
    }

    /**
     * 批量删除供应商结算单
     *
     * @param ids 需要删除的供应商结算单主键
     * @return 结果
     */

    @Override
    public int deleteErpSupplierSettlementByIds(Long[] ids) {
        for (Long id : ids) {
            this.deleteErpSupplierSettlementById(id);
        }
        return 1; // 批量删除返回成功
    }

}
